package com.wlb365.admin.modules.devops.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlb365.admin.common.support.controller.BaseController;

import com.wlb365.admin.common.utils.RSATool;
import com.wlb365.admin.modules.devops.dto.IsvRoleDTO;
import com.wlb365.admin.modules.devops.dto.KeysEditDTO;
import com.wlb365.admin.modules.devops.dto.KeysRoleGroupDTO;
import com.wlb365.admin.modules.devops.entity.Keys;
import com.wlb365.admin.modules.devops.service.IsvRoleService;
import com.wlb365.admin.modules.devops.service.KeysService;
import com.wlb365.admin.modules.sys.entity.Dept;
import com.wlb365.admin.modules.sys.service.IDeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.wlb365.admin.common.dto.R;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * ISV秘钥
 * </p>
 *
 * @author
 * @since 2020-04-08 14:05:08
 */
@Slf4j
@RestController
@RequestMapping("devops/keys")
public class KeysController extends BaseController {

    @Autowired
    private KeysService keysService;
    @Autowired
    private IDeptService deptService;
    @Autowired
    private IsvRoleService isvRoleService;

    @RequiresPermissions("devops:keys:index")
    @GetMapping("index")
    public ModelAndView index() {
        return new ModelAndView("devops/isv/keys");
    }

    @GetMapping(value = "edit")
    public ModelAndView edit(Long id) {
        ModelAndView mv = new ModelAndView("devops/isv/keys_edit");
        KeysEditDTO dto = new KeysEditDTO();
        if (id != null) {
            Keys keys = keysService.getById(id);
            Dept dept = deptService.getById(keys.getDeptId());
            BeanUtil.copyProperties(keys, dto);
            dto.setDeptName(dept == null ? "" : dept.getName());
            KeysRoleGroupDTO keysRoleGroupDTO = isvRoleService.selectIsvRoleGroupByIsvId(keys.getId());
            dto.setKeyRole(keysRoleGroupDTO);
        }
        mv.addObject("editInfo", dto);
        return mv;
    }

    @GetMapping(value = "list/data")
    public R listData(Keys keys) {
        Page<Keys> page = keysService.listKeysPage(keys);
        return R.ok(page);
    }

    @RequiresPermissions("devops:keys:add")
    @PostMapping(value = "add")
    public R add(Keys keys, @RequestParam("roleCodes") List<String> roleCodes) {
        keysService.save(keys);

        this.saveRole(keys.getId(), roleCodes);
        return R.ok();
    }

    @RequiresPermissions("devops:keys:del")
    @PostMapping(value = "batchdel")
    public R batchdel(@RequestParam("ids") List<Long> ids) {
        keysService.removeByIds(ids);
        return R.ok();
    }

    @RequiresPermissions("devops:keys:edit")
    @PostMapping(value = "edit")
    public R edit(Keys keys, @RequestParam("roleCodes") List<String> roleCodes) {
        keysService.update(keys, roleCodes);
        return R.ok();
    }

    private void saveRole(Long isvId, List<String> roleCodes) {
        List<IsvRoleDTO> tobeSaveList = roleCodes.stream()
                .map(roleCode -> {
                    IsvRoleDTO rec = new IsvRoleDTO();
                    rec.setIsvId(isvId);
                    rec.setRoleCode(roleCode);
                    return rec;
                })
                .collect(Collectors.toList());
        if (tobeSaveList != null && tobeSaveList.size() > 0) {
            isvRoleService.insertIsvRoleBatch(tobeSaveList);
        }
    }

    @RequiresPermissions("devops:keys:del")
    @PostMapping(value = "del/{id}")
    public R del(@PathVariable Long id) {
        keysService.removeById(id);
        return R.ok();
    }

    @GetMapping(value = "get/{id}")
    public R get(@PathVariable Long id) {
        return R.ok(keysService.getById(id));
    }

    @GetMapping(value = "createRsa")
    R createPubPriKey(Integer keyFormat) {
        try {
            RSATool.KeyFormat format = RSATool.KeyFormat.PKCS8;
            if (keyFormat != null && keyFormat == 2) {
                format = RSATool.KeyFormat.PKCS1;
            }
            RSATool rsaTool = new RSATool(format, RSATool.KeyLength.LENGTH_2048);
            return R.ok(rsaTool.createKeys());
        } catch (Exception e) {
            log.error("生成秘钥失败", e);
            return R.fail("生成秘钥失败");
        }

    }

    @GetMapping(value = "createSecret")
    R createSecret() {
        return R.ok(IdUtil.fastSimpleUUID());
    }

}

